/**
 *
 * Creator: jmdvirus
 */

#include <unistd.h>

#include "cm_service_base.h"

static int notify_call_back_1(int type, void *args)
{
    printf("this is first callback [%d]\n", type);
    return 0;
}

static int notify_call_back_2(int type, void *args)
{
    printf("this is second callback [%d]\n", type);
    return 0;
}

static int notify_call_back_3(int type, void *args)
{
    printf("this is third callback [%d]\n", type);
    return 0;
}

// 实现一个服务

class DemoService : public CMServiceBaseInterface
{
    public:
    DemoService() : CMServiceBaseInterface("demoService")
    {

    }
    virtual ~DemoService() {};

    int init() {
        return 0;
    }
    int deinit() {
        return 0;
    }

    int start() {
        CMServiceBaseInterface::start();
        return 0;
    }

    int stop() {
        CMServiceBaseInterface::stop();
        return 0;
    }

    int ctl(int type, void *args)
    {
        return 0;
    }

    int run() {
        while (!getExited())
        {
            printf("wait run...\n");
            sleep(1);
        }

        return 0;
    }
};

class UseDemo: public CMServiceBaseFunction
{
    public:
    UseDemo() { ds = NULL;}
    int notify(int type, void *args)
    {
        printf("use Demo notify [%d]\n", type);
        return 0;
    }
    void registerService(DemoService *ds_)
    {
        ds = ds_;
    }

    private:
    DemoService *ds;
};

void test_cm_service_base()
{
    DemoService ds;
    UseDemo ud;
    int ret = ds.registerNotify(CMServiceBaseInterface::SERVICE_BASE_ST_STARTED, &ud);
    ret = ds.registerNotify(CMServiceBaseInterface::SERVICE_BASE_ST_STOPPING, &ud);
    ret = ds.registerNotify(CMServiceBaseInterface::SERVICE_BASE_ST_STOPPED, &ud);

    printf("list size = [%d]\n", ret);

    ds.registerNotify(CMServiceBaseInterface::SERVICE_BASE_ST_STARTED, notify_call_back_1);
    ds.registerNotify(CMServiceBaseInterface::SERVICE_BASE_ST_STOPPING, notify_call_back_2);
    ds.registerNotify(CMServiceBaseInterface::SERVICE_BASE_ST_STOPPED, notify_call_back_2);
    ret = ds.registerNotify(CMServiceBaseInterface::SERVICE_BASE_ST_STOPPED, notify_call_back_3);

    printf("list ret 2 = [%d]\n", ret);

    ds.init();
    ds.start();

    printf("wait program to run\n");
    sleep(10);
    printf("go to stop...\n");

    ret = ds.unregisterNotify(CMServiceBaseInterface::SERVICE_BASE_ST_STOPPED, &ud);
    printf("remove ret = [%d]\n", ret);
    ret = ds.unregisterNotify(CMServiceBaseInterface::SERVICE_BASE_ST_STOPPING, notify_call_back_2);
    printf("remove ret 2 = [%d]\n", ret);

    ds.stop();
    ds.deinit();

}

int main(int argc, char **args)
{
    test_cm_service_base();
    return 0;
}
